<template>
  <div class="uploader-container">
    <i class="el-icon-circle-close" @click="handleDelete"></i>
    <el-upload
      class="image-uploader"
      action="#"
      :show-file-list="false"
      :http-request="upload"
    >
      <div class="image-container">
        <el-image
          :src="imageUrl"
          class="preview"
          fit="contain"
          v-if="imageUrl"
        />
        <div v-else class="notification">上传图片</div>
      </div>
    </el-upload>
  </div>
</template>

<script>
const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDyZzwnWkA1odFkRCDBceO3O3MZnWyLjfE',
  SecretKey: 'TfTDYgoF2SnjUqv32qOqHXWJvAPO6nRn'
})
export default {
  props: {
    value: { required: true, type: String }
  },
  computed: {
    imageUrl: {
      get () {
        return this.value
      },
      set (val) {
        this.$emit('input', val)
      }
    }
  },
  methods: {
    handleDelete () {
      this.imageUrl = ''
    },
    upload (res) {
      if (res.file) {
        cos.putObject(
          {
            Bucket: 'gilgamesh-1305724675', // 存储桶
            Region: 'ap-beijing', // 存储桶所在地域
            Key: res.file.name, // 文件名
            StorageClass: 'STANDARD', // 上传模式：标准模式
            Body: res.file // 上传文件对象
          },
          (err, data) => {
            if (data.statusCode === 200) {
              this.$message.success('头像上传成功')
              this.imageUrl = `https:${data.Location}`
            } else this.$message.error('头像上传失败' + `(${err})`)
          }
        )
      }
    }
  }
}
</script>

<style>
.uploader-container{
  width: 100px;
  position: relative;
}

.el-icon-circle-close{
  position: absolute;
  font-size: 18px;
  top: 0;
  right: 0;
  cursor: pointer;
  color: gray;
  z-index: 998;
}

.image-uploader {
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.el-upload {
  width: 100%;
}
.image-uploader:hover .notification {
  color: #409eff;
}
.image-uploader:hover {
  border-color: #409eff;
}
.image-uploader:not(:hover) .notification {
  color: black;
}
.image-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
  text-align: center;
}
</style>
